package com.jd.finance.oss.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
public class TaskExecutorConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        final int corePoolSize = Runtime.getRuntime().availableProcessors();
        // 最大线程数，默认为Integer.MAX_VALUE
        final int maxPoolSize = corePoolSize * 5; // 5倍
        // 队列最大长度，一般需要设置值>=notifyScheduledMainExecutor.maxNum；默认为Integer.MAX_VALUE
        final int queueCapacity = 5;

        log.info("smartExecutorCorePoolSize:" + corePoolSize);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize); // 线程池的核心大小
        executor.setMaxPoolSize(maxPoolSize);   // 线程池的最大数量
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("smartExecutor-"); //线程池的名称  可以自己定义
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略，超过最大线程数，改为同步
        executor.initialize();
        return TtlExecutors.getTtlExecutor(executor);
    }

    /**
     * 自定义异常处理器
     *
     * @return 异常处理器对象
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("线程调用出错:" + method.getName(), ex);
    }


}